﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ModelQuality.Metrics.Engine;
using ModelQuality.Metrics.Utils;
using log4net;
using System.Reflection;

namespace ModelQuality.Metrics.Rules
{
    abstract partial class ValidationRule
    {
        private static readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
        
        protected IValidationContext context;

        // NOTE: as it is a partial class we cannot declare 2 constructors

        private IList<ValidationResult> results = new List<ValidationResult>();

        private Func<ValidationResult, bool> isOK = res => res.Status == ValidationStatus.OK;
        private Func<ValidationResult, bool> isKO = res => res.Status == ValidationStatus.KO;

        public bool Active
        {
            get { return active; }
        }

        public abstract IList<ValidationRule> GetSubRules();

        /// <summary>
        /// Return true if rule must is applied on all elements
        /// found for its selector, instead of a single element
        /// Ex: Name unicity rule
        /// Default: false
        /// This triggers rule to be called at the end of the validation
        /// run to evaluate itself via EvaluateGlobaly
        /// </summary>
        /// <returns></returns>
        public virtual bool IsGlobal()
        {
            return false;
        }

        /// <summary>
        /// See IsGlobal
        /// Store information to be used later in EvaluateGlobalRule
        /// </summary>
        public virtual void ProcessGlobalRule(Object objectToValidate)
        {
            // do nothing
        }

        /// <summary>
        /// See IsGlobal
        /// Check if information store with ProcessGlobalRule is correct
        /// </summary>
        public virtual ValidationResult EvaluateGlobalRule()
        {
            return null;
        }

        public virtual void Reset()
        {
            results.Clear();
            GetSubRules().ToList().ForEach(subRule => subRule.Reset());
        }

        public bool HasBeenRun()
        {
            return results.Any();
        }

        public void ProcessResult(ValidationResult result)
        {
            results.Add(result);
        }

        public ValidationMessage GetMainMessage()
        {
            return new ValidationMessage("validation_main_" + id, results.Count(isKO));
        }

        public int GetMark()
        {
            log.DebugFormat("Calculating mark for rule {0}", this);
            int mark;

            if (IsMaster())
            {
                var subRules = GetSubRules().Where(subRule => subRule.HasBeenRun());
                if (type == RuleType.BINARY)
                {
                    var subMarks = subRules.Select(rule => rule.GetUnitaryMark());
                    mark = subMarks.Contains(0) ? 0 : 100;
                }
                else
                {
                    int nbOK = subRules.Sum(rule => rule.results.Count(isOK));
                    int total = subRules.Sum(rule => rule.results.Count);
                    mark = AppUtils.GetPercent(nbOK, total);
                }
            }
            else
            {
                mark = GetUnitaryMark();
            }

            log.DebugFormat("Mark for rule {0}: {1}", this, mark);
            return mark;
        }

        private bool IsMaster()
        {
            return GetSubRules().Any(subRule => subRule.active);
        }

        private int GetUnitaryMark()
        {
            log.DebugFormat("Calculating unitary mark for rule {0}", this);
            int mark;

            if (type == RuleType.BINARY)
            {
                mark = results.Any(isKO) ? 0 : 100;
            }
            else
            {
                int nbOK = results.Count(isOK);
                mark = AppUtils.GetPercent(nbOK, results.Count);
            }

            log.DebugFormat("Unitary mark for rule {0}: {1}", this, mark);
            return mark;
        }

        public void SetContext(IValidationContext context)
        {
            this.context = context;
        }
    }
}
